/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

import { h, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { NButton, useDialog } from 'naive-ui'
import { EyeOutlined, EyeInvisibleOutlined } from '@vicons/antd'
import { useAsyncState } from '@vueuse/core'
import {
  queryUserListPaging,
  deleteUser,
  batchDeleteUser,
  updateUser
} from '@/service/modules/user'
import ShowEdit from './components/show-edit'

export function useTable() {
  const { t } = useI18n()
  const dialog = useDialog()

  const variables = reactive({
    columns: [],
    checkedRowKeys: ref([]),
    tableWidth: 500,
    tableData: [],
    pageNo: ref(1),
    pageSize: ref(10),
    searchVal: ref(''),
    totalElements: ref(0),
    totalPage: ref(1),
    showAddModalRef: ref(false),
    showResetModalRef: ref(false),
    statusRef: ref(0),
    row: {},
    loadingRef: ref(false)
  })

  const onHandleReset = (row: any) => {
    variables.showResetModalRef = true
    variables.row = row
  }

  const onHandleDelete = (row: any) => {
    const d = dialog.warning({
      title: `${t('user.delete_tips')}${row.userName}`,
      positiveText: t('common.delete'),
      negativeText: t('user.cancel'),
      onPositiveClick: () => {
        d.loading = true
        return new Promise((resolve) => {
          deleteUser(row.id).then(() => {
            resolve(true)
            getTableData()
          })
        })
      }
    })
  }

  const handleBatchDelete = () => {
    const batchUsers = variables.tableData
      .filter((item: any) => {
        return variables.checkedRowKeys.find((i: any) => i === item.id)
      })
      .map((item: any) => {
        return item.userName
      })
    const d = dialog.warning({
      title: `${t('user.delete_tips')}${batchUsers.toString()}`,
      positiveText: t('common.delete'),
      negativeText: t('user.cancel'),
      onPositiveClick: () => {
        d.loading = true
        return new Promise((resolve) => {
          batchDeleteUser(variables.checkedRowKeys.toString()).then(() => {
            resolve(true)
            getTableData()
          })
        })
      }
    })
  }

  const handleCheck = (rowKeys: any) => {
    variables.checkedRowKeys = rowKeys
  }

  const onShowPassword = (index: number) => {
    ;(variables.tableData[index] as any).showPassword = true
  }

  const onHidePassword = (index: number) => {
    ;(variables.tableData[index] as any).showPassword = false
  }

  const createColumns = (variables: any) => {
    variables.columns = [
      {
        type: 'selection'
      },
      {
        title: t('user.username'),
        key: 'userName'
      },
      {
        title: t('user.password'),
        key: 'userPassword',
        render(row: any, index: number) {
          // const onHidePassword = () => (showPasswordRef.value = false)
          return h(
            'div',
            {
              style:
                'display: flex; flex-direction: row; justify-content: space-between;'
            },
            [
              h('span', row.showPassword ? row.userPassword : '********'),
              row.showPassword
                ? h(
                    NButton,
                    {
                      circle: true,
                      ghost: true,
                      bordered: false,
                      size: 'tiny',
                      type: 'info',
                      style: {
                        'margin-left': '0px'
                      },
                      onClick: () => {
                        onHidePassword(index)
                      }
                    },
                    {
                      icon: () => h(EyeInvisibleOutlined)
                    }
                  )
                : h(
                    NButton,
                    {
                      circle: true,
                      ghost: true,
                      bordered: false,
                      size: 'tiny',
                      type: 'info',
                      onClick: () => {
                        onShowPassword(index)
                      }
                    },
                    {
                      icon: () => h(EyeOutlined)
                    }
                  )
            ]
          )
        }
      },
      {
        title: t('user.description'),
        key: 'description',
        render(row: any, index: number) {
          return h(ShowEdit, {
            value: row.description,
            updateEdit: (v: any) => {
              variables.tableData[index].description = v
              updateUser(row.id, v).then(() => {
                getTableData()
              })
            }
          })
        }
      },
      {
        title: t('common.action'),
        key: 'actions',
        render(row: any) {
          return h('span', null, [
            h(
              NButton,
              {
                text: true,
                type: 'info',
                strong: true,
                size: 'small',
                onClick: () => {
                  onHandleReset(row)
                }
              },
              { default: () => t('user.reset') }
            ),
            h(
              NButton,
              {
                text: true,
                type: 'info',
                strong: true,
                size: 'small',
                style: {
                  'margin-left': '10px'
                },
                onClick: () => {
                  onHandleDelete(row)
                }
              },
              { default: () => t('common.delete') }
            )
          ])
        }
      }
    ]
  }

  const getTableData = () => {
    const { state, isLoading } = useAsyncState(
      queryUserListPaging(
        variables.pageNo,
        variables.pageSize,
        variables.searchVal
      ).then((res: any) => {
        variables.tableData = res.content.map((item: any) => {
          return {
            ...item,
            showPassword: false
          }
        })
        variables.totalElements = res.totalElements
        variables.totalPage = Math.ceil(res.totalElements / variables.pageSize)
      }),
      [] as any
    )
    return { state, isLoading }
  }

  return {
    variables,
    createColumns,
    getTableData,
    handleCheck,
    handleBatchDelete
  }
}
